/**
 * 
 */
package com.ccqlk.attendance.config.spirng;

import java.util.Properties;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;

import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * Copyright 2015-2018 重庆鲁控科技有限公司<br>
 * 文件标题: SpringConfig<br>
 * 文件说明: TODO<br>
 * @author ZhangYinxian 348893009@qq.com<br>
 * 创建时间 2016年5月26日 下午11:40:13<br>
 */
@Configuration
@ComponentScan({"com.ccqlk.attendance.repository.service"})
@PropertySource("classpath:resources.properties")
public class SpringConfig implements EnvironmentAware {
   
	private Environment environment;

	@Bean(name="dataSource", destroyMethod="close")
	public DruidDataSource dataSource(){
		
		DruidDataSource druidDataSource = new DruidDataSource();
		
		druidDataSource.setUrl(environment.getProperty("jdbc.url"));
		druidDataSource.setUsername(environment.getProperty("jdbc.username"));
		druidDataSource.setPassword(environment.getProperty("jdbc.password"));
		
		return druidDataSource;
	}
	
	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception{
		
		PageHelper pageHelper = new PageHelper();
		
		Properties p = new Properties();
		p.setProperty("dialect", "mysql");
		pageHelper.setProperties(p);

		
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource());
		
		sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
		
		return sqlSessionFactoryBean.getObject();
	}
	
	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer(){
		
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setBasePackage("com.ccqlk.attendance.repository.dbservice");
		
		return mapperScannerConfigurer;
	}

	/* (non-Javadoc)
	 * @see org.springframework.context.EnvironmentAware#setEnvironment(org.springframework.core.env.Environment)
	 */
	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
}
